<template>
    <div style="padding-bottom: 60px;">
        <Card dis-hover >
            <Row :gutter="8" class="ivu-mb-8">
                <!-- :options="options" -->
                <Col>
                <Select v-model="params.project_id" v-width="200" placeholder="所有项目" clearable @on-change="askData">
                    <Option v-for="item in projectList" :value="item.project_id" :key="item.project_id">{{ item.name }}</Option>
                </Select>
                </Col>
                <Col style="color:#ff9900;line-height:40px;">
                <!-- <Icon type="md-alert" color="#ff9900"></Icon>2022年7月26日前数据不完善，不参与数据匹配 -->
                </Col>
            </Row>

            <Row :gutter="8" class="ivu-mb-8">
                <Col>
                <Card dis-hover >
                    <!--                        <h3 class="ivu-mb-8">匹配词报告</h3>-->
                    <Row :gutter="8" class="ivu-mb-8">
                        <Col>
                        <DatePicker type="daterange"
                                    v-model="params.arrdate"
                                    class="ivu-mr-8"
                                    ref="date"
                                    @on-change="changeParams"
                                    placeholder="请选择时间段"
                                    :time-picker-options="{steps: [1, 10, 10]}"
                                    v-width="200"
                                    :clearable="false"
                                    :options="dateOption"
                                    @click.native="nativeClick"
                        ></DatePicker>
                            </Col>
                        <Col>
                        <Button type="primary" @click="exportData"
                                :loading="exportLoading"
                                v-hasC="{
                                    name: 'v1-search-search-export-keywords-report',
                                    flag: 'v1/search/search/export-keywords-report',
                        }">
                            导出
                        </Button>
                            </Col>
                    </Row>

                    <u-table
                        :data="matchData"
                        use-virtual
                        :max-height="700"
                        show-summary
                        :summary-method="summaryMethod"
                    >
                        <u-table-column prop="id" label="编号" min-width="40"></u-table-column>
                        <u-table-column prop="keyword" label="搜索词" min-width="250" show-overflow-tooltip></u-table-column>
                        <u-table-column prop="total" label="出现次数" min-width="40"></u-table-column>
                        <u-table-column prop="send_total" label="开口数" min-width="40"></u-table-column>
                        <u-table-column prop="effect_total" label="有效对话数" min-width="40"></u-table-column>
                        <u-table-column prop="five_total" label="5星对话数" min-width="40"></u-table-column>
                    </u-table>
                </Card>
                </Col>
            </Row>
        </Card>
    </div>
</template>
<script>
    import { keywordsSearch, keywordsExport } from '@/api/hqapi';
    import dayjs from 'dayjs';
    import { UTable, UTableColumn } from 'umy-ui';
    import {export_json_to_excel} from '../../../assets/excel/Export2Excel';

    export default {
        components: {
            UTable,
            UTableColumn,
        },
        data(){
            return {
                params: {
                    project_id: '',
                    date: [],
                    arrdate: []
                },
                dateOption: {
                    disabledDate(date) {
                        return date && date.valueOf() > Date.now();
                    }
                },
                loading: false,
                exportLoading: false,
                projectList: [],
                matchData: [],
                totalArr: {
                    id: '总计',
                    keyword: '',
                    total: '',
                    send_total: '',
                    effect_total: '',
                    five_total: ''
                },
            };
        },
        mounted() {
            let nowDate = new Date();
            let yesterday = new Date(dayjs(nowDate.getTime() - 86400 * 1000).format('YYYY-MM-DD'));
            this.params.date = [yesterday, yesterday];
            this.params.arrdate = [yesterday, yesterday];
            this.initial();
        },
        methods: {
            initial() {
                this.projectList = JSON.parse(localStorage.getItem('project'));
                this.askData();
            },
            askData(){
                this._getmatching();
            },
            // 获取搜索词列表
            _getmatching(){
                this.loading = true;
                const params = {
                    project_id: this.params.project_id,
                    start_time: dayjs(this.params.arrdate[0]).format('YYYY-MM-DD'),
                    end_time: dayjs(this.params.arrdate[1]).format('YYYY-MM-DD'),
                };
                keywordsSearch(params).then(res => {
                    // let cc = {
                    //     id: '总计',
                    //     keyword: res.list.length + '组',
                    //     total: res.total,
                    //     send_total: res.send_total,
                    // };
                    this.totalArr.keyword = res.list.length + '组';
                    this.totalArr.total = res.total;
                    this.totalArr.send_total = res.send_total;
                    this.totalArr.effect_total = res.effect_total;
                    this.totalArr.five_total = res.five_total;
                    // const arr = res.list;
                    // arr.push(cc);
                    this.matchData = res.list;
                    this.loading = false;
                }).catch(err => {
                    this.loading = false;
                });

            },
            // 日期下拉选择
            changeParams(){
                this._getmatching();
            },
            // 限制31天选择范围
            nativeClick(e){
                const target = this.$refs['date'].$refs['pickerPanel'];
                target.handlePickClick = () => { // 这里加这么一段
                    const { from, selecting } = target['rangeState'];
                    if(from && selecting) {
                        this.dateOption = {
                            disabledDate(value) {
                                const startTime = new Date(from);
                                const endTime = new Date(from);
                                startTime.setDate(from.getDate() - 30);
                                endTime.setDate(from.getDate() + 30);
                                return !(value >= startTime && value <= endTime);
                            }
                        };
                    }
                };
                const { from, selecting } = target['rangeState'];
                if(from && selecting) {
                    this.dateOption = {
                        disabledDate(value) {
                            const startTime = new Date(from);
                            const endTime = new Date(from);
                            startTime.setDate(from.getDate() - 30);
                            endTime.setDate(from.getDate() + 30);
                            return !(value >= startTime && value <= endTime);
                        }
                    };
                }else {
                    this.dateOption = {
                        disabledDate(date) {
                            return date && date.valueOf() > Date.now();
                        }
                    };
                }
            },
            exportData(){
                this.exportLoading = true;

                require.ensure([], () => {
                    const { export_json_to_excel } = require('../../../assets/excel/Export2Excel');

                    let thead = ['编号', '搜索词', '出现次数', '开口数', '有效对话数','5星对话数'];
                    let data = [];
                    for(let key in this.matchData) {
                        let row_data = [
                            parseInt(key) + 1,
                            this.matchData[key].keyword,
                            this.matchData[key].total,
                            this.matchData[key].send_total,
                            this.matchData[key].effect_total,
                            this.matchData[key].five_total,
                        ];
                        data.push(row_data);
                    }
                    // 总计
                    data.push([this.totalArr.id, this.totalArr.keyword, this.totalArr.total, this.totalArr.send_total, this.totalArr.effect_total,this.totalArr.five_total]);

                    export_json_to_excel(thead, data, '搜索词报告');
                    setTimeout(() => {
                        this.exportLoading = false;
                    }, 400);
                });
            },
            // 表格尾部渲染
            summaryMethod({ columns, data }) {
                return [[this.totalArr.id, this.totalArr.keyword, this.totalArr.total, this.totalArr.send_total, this.totalArr.effect_total,this.totalArr.five_total]];
            }
        }
    };
</script>